//
//  StatusPicturesView.swift
//  ShangHaiWeiBo
//
//  Created by 蔡杰 on 16/3/3.
//  Copyright © 2016年 蔡杰. All rights reserved.
//

import UIKit

class StatusPicturesView: UIView {
    
    var pic_urls: [StatusPictures]? {
    
        didSet{
        
            for v in subviews{
            
                v.hidden = true
            }
            var index = 0
            for url in (pic_urls ?? []){
            
                let iv = subviews[index++] as! UIImageView
                
                iv.cz_setImageWithURL(url.thumbnail_pic, placeholderName: nil )
                iv.hidden = false
                
                if index == 2 && pic_urls?.count == 4{
                
                    index++
                }
            }
        }
    }
    func updateImageSize(size:CGSize){
    
        let iv = subviews[0]
        
        if pic_urls?.count == 1{
        
            iv.frame = CGRect(origin: CGPointZero, size: size)
//            iv.clipsToBounds = true
//            iv.contentMode = .ScaleAspectFill
            sizeToFit()
            return
        }
        
        iv.frame = CGRect(origin: CGPointZero, size: CZStatusCellLayout.pictureSize)

    }
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension StatusPicturesView {
    
    private func setupUI(){
        
        backgroundColor = UIColor.whiteColor()
        
        clipsToBounds = true
        // 1. 添加 `9` 个图像视图
        // 每张图像的bounds
        let rect = CGRect(origin: CGPointZero, size: CZStatusCellLayout.pictureSize)
        // 移动步长
        let step = CZStatusCellLayout.pictureSize.width + CZStatusCellLayout.picturesMargin
        
        for i in 0..<9 {
            let iv = UIImageView()
            
            // 设置内容填充模式 .ScaleAspectFit 在九宫格能够产生犬牙交错的效果
            iv.contentMode = .ScaleAspectFill
            
            iv.clipsToBounds = true
            
            // 设置视图的位置
            // 1> 根据 i 计算出每张图片所在的行和列
            let row = CGFloat(i / Int(CZStatusCellLayout.picturesPerRow))
            // `模`数
            let col = CGFloat(i % Int(CZStatusCellLayout.picturesPerRow))
            
            // 2> 设置位置
            iv.frame = CGRectOffset(rect, col * step, row * step)
            
            addSubview(iv)
        }

    }
    
}

